// 使用 Express 创建一个服务器
const express = require('express')
const bodyParser = require('body-parser')
const open = require('open')
const util = require('../util/util')

const app = express()
const port = 3031

app.use(express.static(__dirname + '/../public'))

//加载解析json的中间件
app.use(bodyParser.json({ limit: '999999999kb' }))

//加载解析urlencoded请求体的中间件
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
)

function init({ dir, langPath }) {
  
  open('http://localhost:3031/', 'chrome')

  app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('Content-Type', 'application/json;charset=utf-8')
    if (req.method == 'OPTIONS') {
      //  antd中 需要去掉 credentials: 'include'
      res.sendStatus(200) /* 让options请求快速返回*/
    } else {
      next()
    }
  })

  // 服务器端渲染 React 应用
  app.get('/get', (req, res) => {
    try {
      const langFiles = util.readLangFiles(langPath, dir)
      res.send({
        success: true,
        data: langFiles,
      })
    } catch (error) {
      console.log(error)
      res.send({
        success: false,
        msg: '请求失败',
      })
    }
  })
  
  app.post('/set', (req, res) => {
    try {
      if (!req.body || !req.body.data || typeof req.body.data !== 'object') {
        res.send({
          success: false,
          msg: '未获取到有效参数',
        })
        return
      }
      util.saveLangFiles(langPath, dir, req.body.data)

      res.send({
        success: true,
        msg: '保存成功',
      })
    } catch (error) {
      console.log(error)
      res.send({
        success: false,
        msg: '保存失败',
        error: error,
      })
    }
  })

  app.listen(port, () => {
    console.log(`已启动服务，请访问 http://localhost:${port} 编辑国际化文本`)
  })
}

module.exports = init
